package org.visionlibrary.image.geomtric.model;

import java.util.BitSet;

import javax.media.jai.TiledImage;


public class Mask2d {
	BitSet[] data = null;
	private int pointsSet = 0;
	private int xLength = 0;
	private int yLength = 0;

	public Mask2d(int xLength, int yLength) {
		pointsSet = 0;
		this.xLength = xLength;
		this.yLength = yLength;

		data = new BitSet[xLength];
		for (int x = 0; x < xLength; x++)
			data[x] = new BitSet(yLength);
	}

	public Mask2d(Mask2d old) {
		this.pointsSet = old.pointsSet;
		this.xLength = old.xLength;
		this.yLength = old.yLength;

		this.data = new BitSet[this.xLength];

		for (int x = 0; x < this.xLength; x++)
			data[x] = (BitSet) old.data[x].clone();
	}

	public void recount() {
		pointsSet = 0;
		for (int x = 0; x < data.length; x++)
			for (int i = data[x].nextSetBit(0); i >= 0; i = data[x]
					.nextSetBit(i + 1))
				pointsSet++;
	}

	public void invert() {
		for (int x = 0; x < data.length; x++)
			data[x].flip(0, yLength - 1);
		pointsSet = xLength * yLength - pointsSet;
	}

	public void set(int x, int y) {
		if (!get(x, y)) {
			pointsSet++;
			data[x].set(y);
		}
	}

	public void set(Point2d p) {
		if (!get(p)) {
			pointsSet++;
			data[p.getXAsInt()].set(p.getYAsInt());
		}
	}

	public void unSet(int x, int y) {
		if (get(x, y)) {
			pointsSet--;
			data[x].clear(y);
		}
	}

	public void unSet(Point2d p) {
		if (get(p)) {
			pointsSet--;
			data[p.getXAsInt()].clear(p.getYAsInt());
		}
	}

	public boolean get(int x, int y) {
		return data[x].get(y);
	}

	public boolean get(Point2d p) {
		return data[p.getXAsInt()].get(p.getYAsInt());
	}

	public int getPointsSet() {
		return pointsSet;
	}

	public int width() {
		return xLength;
	}

	public int height() {
		return yLength;
	}

	public static Mask2d createForegroundMask(TiledImage image,
			int[] backgroundColor) {
		Mask2d mask = new Mask2d(image.getWidth(), image.getHeight());
		for (int x = 0; x < mask.xLength; ++x) {
			for (int y = 0; y < mask.yLength; ++y) {
				boolean background = true;
				for (int i = 0; i < backgroundColor.length; ++i) {
					if (backgroundColor[i] != (image.getSample(x, y, i)&0xffffff)) {
						background = false;
						break;
					}
				}
				if (!background) {
					mask.set(x, y);
				}
			}
		}
		return mask;
	}
}
